<template>
	<view class="page-live" @touchmove.stop="">
		<view class="live-header cu-btn round bg-red" :style="{height: Custom?`${Custom.height}px`:'50rpx',top:Custom?`${Custom.top}px`:'20rpx'}">
			在线人数：{{client_total}}
		</view>

		<live-pusher id='livePusher' ref="livePusher" class="livePusher" :url="livePusher.obs_url" :mode="liveOptions.definition"
		 :muted="isMuted" :enable-camera="true" :device-position="liveOptions.camera" :autopush="true" :auto-focus="true"
		 :beauty="4" whiteness="2" aspect="9:16" @statechange="statechange" @netstatus="netstatus" @error="error" style="width: 100vw; height: 100vh;"></live-pusher>

		<!-- 弹幕 -->
		<view class="live-wrap padding">
			<scroll-view scroll-y :scroll-top="scrollTop" id="msg" class="msg-wrap">
				<block v-for="(item,index) of client_msg_list" :key="index">
					<view class="tip msg-item" v-if="item.type===1">
						<view class="bg-red text-white padding-xs tip-cont">
							<text>{{item.content}}</text>
						</view>
					</view>
					<view class="tip msg-item" v-if="item.type===4">
						<view class="bg-red text-white padding-xs tip-cont">
							<text>{{item.content}}</text>
						</view>
					</view>
					<view class="live-cont msg-item">
						<view class="live-cont-item padding-lr-xs" v-if="item.type===2">
							<text class="text-red">{{item.name}}</text>
							<text class="margin-left-xs">{{item.content}}</text>
						</view>
						<view class="live-cont-item padding-lr-xs" v-if="item.type===3">
							<text class="text-red">公告：</text><text>{{item.content}}</text>
						</view>
					</view>
				</block>
			</scroll-view>
		</view>
		<!-- 底部菜单 -->
		<view class="menu padding">
			<view class="menu-left">
				<view class="menu-item" @click="switchCamera">
					<image src="@/static/icons/live-camera.png" />
					<text>切换</text>
				</view>
				<view class="menu-item margin-left-sm" style="background: #666;" @click="toggleMuted" v-if="isMuted">
					<image src="@/static/icons/live-voice.png" />
					<text>静音</text>
				</view>
				<view class="menu-item margin-left-sm" @click="toggleMuted" v-else>
					<image src="@/static/icons/live-voice.png" />
					<text>静音</text>
				</view>
			</view>
			<view class="menu-right">
				<view class="menu-item" @click="handleStopLive">
					<image src="@/static/icons/live-stop.png" />
					<text>结束</text>
				</view>

			</view>
		</view>
		<!-- <button class="btn" @click="start">开始推流</button>
		<button class="btn" @click="pause">暂停推流</button>
		<button class="btn" @click="resume">resume</button>
		<button class="btn" @click="stop">停止推流</button>
		<button class="btn" @click="snapshot">快照</button>
		<button class="btn" @click="startPreview">开启摄像头预览</button>
		<button class="btn" @click="stopPreview">关闭摄像头预览</button>
		<button class="btn" @click="switchCamera">切换摄像头</button> -->
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex"
	export default {
		data() {
			return {
				fil: true,
				isMuted: false,
				client_msg_list: [], //当前在线消息数据
				scrollTop: 0,
				client_total: 0,
				hasToasted: false
			}
		},
		computed: {
			...mapState('live', ['livePusher', 'liveOptions']),
		},
		methods: {
			//监听直播变化
			statechange(e) {
				console.log("statechange:" + JSON.stringify(e));
			},
			netstatus(e) {
				console.log("netstatus:" + JSON.stringify(e));
			},
			error(e) {
				console.log("error:" + JSON.stringify(e));
			},
			//开始
			start() {
				this.context.start({
					success: (a) => {
						console.log("livePusher.start:" + JSON.stringify(a));
					}
				});
			},
			//关闭
			close() {
				this.context.close({
					success: (a) => {
						console.log("livePusher.close:" + JSON.stringify(a));
					}
				});
			},
			//截图
			snapshot() {
				this.context.snapshot({
					success: (e) => {
						console.log(JSON.stringify(e));
					}
				});
			},
			resume() {
				this.context.resume({
					success: (a) => {
						console.log("livePusher.resume:" + JSON.stringify(a));
					}
				});
			},
			//暂停
			pause() {
				this.context.pause({
					success: (a) => {
						console.log("livePusher.pause:" + JSON.stringify(a));
					}
				});
			},
			//停止推流
			stop() {
				this.context.stop({
					success: (a) => {
						console.log(JSON.stringify(a));
					}
				});
			},
			//切换摄像头
			switchCamera() {
				this.context.switchCamera({
					success: (a) => {
						console.log("livePusher.switchCamera:" + JSON.stringify(a));
					}
				});
			},
			startPreview() {
				this.context.startPreview({
					success: (a) => {
						console.log("livePusher.startPreview:" + JSON.stringify(a));
					}
				});
			},
			stopPreview() {
				this.context.stopPreview({
					success: (a) => {
						console.log("livePusher.stopPreview:" + JSON.stringify(a));
					}
				});
			},
			//控制静音
			toggleMuted() {
				this.isMuted = !this.isMuted
			},
			//结束直播
			async handleStopLive() {
				let query = {
					op: 'n'
				}
				let {
					code
				} = await this.$h.api.liveModel.postLiveState(query)
				if (code === 1) {
					this.stop()
					this.$h.router.back()
				}
			},
			//添加信息到视图
			handleAppend(item) {
				this.client_msg_list.push(item)
				//自动滚动到最底部
				this.scrollToBottom()
			},
			scrollToBottom() {
				this.$nextTick(function() {
					const query = uni.createSelectorQuery().in(this);
					let that = this
					let scrollHeight = 0
					query.selectAll('.msg-item').boundingClientRect(res => {
						res.forEach(rect => scrollHeight += rect.height)
						that.scrollTop = scrollHeight
					}).exec();
				})
			},
			initConnect() {
				this.$h.wb.initConect().then(res => {
					if (res) {
						this.onMsg()
						this.handleConnect()
					} else {
						this.initConnect()
					}
				})
			},
			handleConnect() {
				let query = {
					type: "login",
					client_name: this.userInfo.nickname,
					room_id: this.livePusher.id
				}
				//创建websocket房间链接
				this.$h.wb.send(JSON.stringify(query)).then(res => {
					console.log(res)
				})
			},
			//接受websocket的信息
			onMsg() {
				this.$h.wb.socketTask.onMessage(e => {
					var data = JSON.parse(e.data);
					console.log("on", data);
					console.log(e)
					switch (data.type) {
						// 服务端ping客户端
						case 'ping':
							this.$h.wb.send('{"type":"pong"}');
							break;
							// 登录 更新用户列表
						case 'login':
							// 主播不需要提示
							if (data.client_name !== this.userInfo.nickname) {
								this.handleAppend({
									type: 1,
									content: data.client_name + "进入直播间"
								});
							}
							break;
							// 发言
						case 'say':
							this.handleAppend({
								type: 2,
								name: data.from_client_name,
								content: data.content
							})
							break;
							// 用户离开 更新用户列表
						case 'logout':
							// 主播不需要提示
							// this.handleAppend({
							// 	type: 1,
							// 	content: data.from_client_name + "离开了直播间",
							// });
							break;
						case 'living':
							this.client_total = data.play_num;
							break;
						case 'live_status':
							this.live_status = data.status;
							this.checkLiveStatus()
							break;
						case 'reward':
							this.handleAppend({
								type: 4,
								content: data.content
							})
							break;
					}
				})
			},
			checkLiveStatus() {
				if (this.hasToasted) {
					return
				}
				if (this.live_status != 1) {
					this.hasToasted = true
					this.$h.toast("直播已关闭"+this.live_status).then(()=>{
						this.$h.router.back()
					})
				}
			},
		},
		onLoad() {
			this.initConnect()
		},
		onReady() {
			// 注意：需要在onReady中 或 onLoad 延时
			this.context = uni.createLivePusherContext("livePusher", this);
		},
		onShow() {
			//屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		beforeDestroy() {
			if (this.$h.wb.status === 'open') {
				this.$h.wb.closeConnect()
			}
		},
		onPush(ret) {
			if (ret.detail.code == 1002) {
				console.log('推流成功了', ret);
			}
		},
	}
</script>

<style lang="scss" scoped>
	.page-live {
		width: 100vw;
		height: 100vh;
		background: #000;

		.live-header {
			position: fixed;
			left: 20rpx;
			z-index: 10000;
			padding: 0 10rpx;
			box-sizing: border-box;
			font-size: 20rpx;

			@include df-row($jc: space-between, $ai:center) .avatar {
				width: 25px;
				height: 25px;
			}
		}

		.live-wrap {
			height: 350rpx;
			position: fixed;
			left: 0;
			bottom: 200rpx;

			.msg-wrap {
				height: 100%;
				@include df-col()
			}

			.tip {
				min-width: 166rpx;
				margin-bottom: 10rpx;

				&-cont {
					border-radius: 5px;
					font-size: 24rpx;
				}
			}

			.live-cont {
				@include df-col();

				&-item {
					max-width: 300rpx;
					background: rgba(51, 51, 51, 0.3);
					border-radius: 5px;
					font-size: 24rpx;
					margin: 10rpx 0;
					color: #fff;
				}
			}
		}

		.menu {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			@include df-row($jc: space-between, $ai: center);

			&-left {
				@include df-row($ai: center);

			}

			&-right {
				@include df-row($ai: center)
			}

			.menu-item {
				width: 50px;
				height: 50px;
				background: rgba(52, 52, 54, 1);
				border-radius: 50%;
				@include df-col($jc: center, $ai:center);
				color: #fff;
				font-size: 20rpx;

				image {
					@include build-square(46rpx)
				}
			}
		}
	}
</style>
